<template>
    <div class="execution">
        <basic-container>
            <style-page
                :showTabsRight='false'
                :showTabsHeard='false'
            >
                <template slot="tabs">
                    <avue-crud ref="crud"
                        :page.sync="page"
                        :data="tableData"
                        :permission="permissionList"
                        :table-loading="tableLoading"
                        :option="tableOption"
                        @on-load="getList"
                        @search-change="searchChange"
                        @refresh-change="refreshChange"
                        @size-change="sizeChange"
                        @current-change="currentChange"
                        @row-update="handleUpdate"
                        @row-save="handleSave"
                        @row-del="rowDel"
                        @selection-change="selectionChange">
                        <template slot-scope="scope" slot="menu">
                            <el-link
                                icon='el-icon-edit'
                                style="margin-left:20px;font-size:12px;font-weight:100"
                                type="primary"
                                @click.stop="handleEdit(scope.row,'edit')"
                                >编辑</el-link
                            >
                            <el-link
                                icon='el-icon-view'
                                style="margin-left:20px;font-size:12px;font-weight:100"
                                type="primary"
                                @click.stop="handleEdit(scope.row,'read')"
                                >查看</el-link
                            >
                            <el-link
                                icon='el-icon-edit'
                                style="margin-left:20px;font-size:12px;font-weight:100"
                                type="primary"
                                @click.stop="handleEdit(scope.row,'next')"
                                >跟进</el-link
                            >
                            <!--<el-link
                                style="margin-left:20px"
                                type="primary"
                                @click.stop="rowDel(scope.row,scope.index)"
                                >删除</el-link
                            > -->
                        </template>
                        <template slot="menuLeft">
                            <el-button type="primary" @click="handleEdit(null,'addbusinessfollow')" size='small'>商机新增</el-button>
                            <el-button type="primary" @click="handleEdit(null,'omsbusinessfollow')" size='small'>商机跟进</el-button>
                            <el-button type="primary" @click="handerAuthorization" size='small'>产品授权</el-button>
                            <el-button type="primary" @click="handleEdit(null,'omsbusinessperson')" size='small'>添加协作人</el-button>
                            <el-button type="primary" @click="handleEdit(null,'omsbusinesstransfer')" size='small'>商机转移</el-button>
                            <el-button type="primary" size='small'>删除</el-button>
                        </template>
                    </avue-crud>
                </template>
            </style-page>

            <!-- 产品授权弹框 -->
            <el-dialog
            title="请选择商品"
            :visible.sync="dialogVisible"
            width="80%"
            destroy-on-close>
                <el-dialog
                width="70%"
                title="商品结算"
                :visible.sync="innerVisible"
                append-to-body>
                    <!-- 第二层 -->
                    <div class="tabelUnitBox" v-for=" item in dataList" :key="item.data.id">
                        <div class="tabelUnitBox_header">
                            <h2>产品名称:({{item.data.proName}})</h2>
                            <h4>小计:{{item.data.budgetAmount}}元</h4>
                        </div>
                        <div class="tabelUnitBox_time">
                            <el-date-picker
                            style="width:60%"
                            v-model="item.timeDate"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="yyyy 年 MM 月 dd 日 HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </div>
                        <div class="tabelUnitBox_conter">
                            <businesslicenseoms v-if="innerVisible" :targerId='item.data.id' :firstSelectId='firstSelectId' v-on:secondTableChange='secondTableChange'/>
                        </div>
                    </div>

                    <div class="totalPrices">
                        <h2>优惠金额:0</h2>
                        <h1>结算总价:{{totalPrices}}</h1>
                    </div>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="innerVisible = false">返 回</el-button>
                        <el-button type="primary" @click="addAuthorization">确认并授权</el-button>
                    </span>
                </el-dialog>
                <!-- 第一层 -->
                <omsproductoms v-if="dialogVisible" v-on:firstSelectId='firstSelect'/>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="()=>{this.innerVisible = true}">进行结算</el-button>
                </span>
            </el-dialog>

            <!-- 商机跟进弹框 -->
            <el-dialog v-loading="followLoading" destroy-on-close width="30%" title="商机跟进" :visible.sync="followVisible">
                <el-form :model="followForm" ref='followform'>
                    <el-form-item label="商机当前状态" prop="busStatus">
                        <el-select v-model="followForm.busStatus">
                            <el-option label="新商机" :value="1"></el-option>
                            <el-option label="正在试用" :value="2"></el-option>
                            <el-option label="试用结束" :value="3"></el-option>
                            <el-option label="初步接洽" :value="4"></el-option>
                            <el-option label="方案/报价" :value="5"></el-option>
                            <el-option label="谈判/合同" :value="6"></el-option>
                            <el-option label="赢单" :value="7"></el-option>
                            <el-option label="输单" :value="8"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="本次跟进时间" prop="currentFollowTime">
                        <el-date-picker
                            v-model="followForm.currentFollowTime"
                            type="datetime"
                            placeholder="选择日期时间"
                            format='yyyy-MM-dd HH:mm:ss'
                            value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="下次计划跟进时间" prop="nextFollowTime">
                        <el-date-picker
                            v-model="followForm.nextFollowTime"
                            type="datetime"
                            placeholder="选择日期时间"
                            format='yyyy-MM-dd HH:mm:ss'
                            value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="备注一（非必填）" prop="remark">
                        <el-input v-model="followForm.remark"></el-input>
                    </el-form-item>
                    <el-form-item label="附件上传" prop="file">
                        <el-upload
                            ref="upload"
                            class="upload-demo"
                            action="/api/omsbusinessfollow"
                            :on-change="uploadchange"
                            :limit="1"
                            :auto-upload="false"
                            :data='followForm'
                            :file-list="fileList">
                            <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">支持拓展名：rar、zip、doc、docx、pdf、jpg、png.....</div>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="followVisible = false">取 消</el-button>
                    <el-button type="primary" @click="followUpData">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 添加协作人 -->
            <el-dialog
                title="添加协作人"
                :visible.sync="personVisible"
                v-loading="personLoading"
                width="40%">
                <el-form :model="personForm" ref='personform'>
                    <el-form-item label="责任人" prop='charge'>
                        <el-input disabled v-model="personForm.charge"></el-input>
                    </el-form-item>
                    <el-form-item label="协作人" prop='busAssistPerson'>
                        <el-input v-model="personForm.busAssistPerson"></el-input>
                    </el-form-item>
                    <el-form-item label="备注一（非必填）" prop='remark'>
                        <el-input v-model="personForm.remark"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="personVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addCharge">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 商机转移 -->
            <el-dialog
                title="商机转移"
                :visible.sync="transferVisible"
                v-loading="transferLoading"
                width="40%">
                <el-form :model="transferForm" ref='transferform' prop='charge'>
                    <el-form-item label="责任人">
                        <el-input disabled v-model="transferForm.charge"></el-input>
                    </el-form-item>
                    <el-form-item label="协作人" prop='busAssistPerson'>
                        <el-input disabled v-model="transferForm.busAssistPerson"></el-input>
                    </el-form-item>
                    <el-form-item label="转移对象" prop='transferPerson'>
                        <el-input v-model="transferForm.transferPerson"></el-input>
                    </el-form-item>
                    <el-form-item label="备注一（非必填）" prop='remark'>
                        <el-input v-model="transferForm.remark"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="transferVisible = false">取 消</el-button>
                    <el-button type="primary" @click="transfer">确 定</el-button>
                </span>
            </el-dialog>

        </basic-container>
    </div>
</template>

<script>
    import {
        fetchList, 
        getObj, 
        addObj, 
        putObj, 
        delObj, 
        fetchAuthorization, 
        fetchOmsbusinessfollow,
        fetchOmsbusinessperson,
        fetchOmsbusinesstransfer} from '@/views/saas-business/omsbusiness/api/omsbusiness'
    import {tableOption, peoductTableOption} from '@/views/saas-business/omsbusiness/const/omsbusiness'
    import {mapGetters} from 'vuex'
    import businesslicenseoms from '@/views/saas-business/businesslicenseoms/views/businesslicenseoms/index.vue'
    import omsproductoms from '@/views/saas-business/omsproductoms/views/productoms'
    export default {
        name: 'omsbusiness',
        components:{
            businesslicenseoms,
            omsproductoms,
        },
        data() {
            return {
                searchForm: {},
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 10 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption,
                // 页面表格选择的数据
                tableselect:[],
                // 产品授权弹框
                dialogVisible:false,
                innerVisible:false,
                // 第一层弹窗表格选择的产品id
                firstSelectId:[],
                // 第二层弹窗表格动态数据
                totalPrices:0,
                secondTableData:[],
                // 产品授权根据id返回接口数据
                dataList:[],
                // 商机跟进弹框和表单
                followLoading:false,
                followVisible:false,
                followForm:{
                    busStatus:1,
                    currentFollowTime:'',
                    nextFollowTime:'',
                    remark:'',
                    busId:'',
                    file:'',
                },
                fileList:[],
                // 添加协作人
                personVisible:false,
                personLoading:false,
                personForm:{
                    charge:'',
                    busAssistPerson:'',
                    id:'',
                    remark:'',
                },
                // 商机转移
                transferVisible:false,
                transferLoading:false,
                transferForm:{
                    charge:'',
                    transferPerson:'',
                    id:'',
                    remark:'',
                    busAssistPerson:'',
                },
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.omsbusiness_edit, false),
                    delBtn: this.vaildData(this.permissions.omsbusiness_del, false),
                    editBtn: this.vaildData(this.permissions.omsbusiness_edit, false)
                };
            }
        },
        methods: {
            // 商机转移
            transfer(){
                this.transferLoading = true
                fetchOmsbusinesstransfer(this.transferForm).then(res => {
                    if(res.data.code === 0){
                        this.$message({
                            message: '转移成功',
                            type: 'success'
                        });
                    }else{
                        this.$message({
                            message: '转移失败',
                            type: 'warning'
                        });
                    }
                    debugger
                    this.transferLoading = false
                    this.transferVisible = false
                    this.$refs['transferform'].resetFields()
                })
            },
            // 添加商机协作人
            addCharge(){
                this.personLoading = true
                fetchOmsbusinessperson(this.personForm).then(res => {
                    if(res.data.code === 0){
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                    }else{
                        this.$message({
                            message: '添加失败',
                            type: 'warning'
                        });
                    }
                    this.personLoading = false
                    this.personVisible = false
                    this.$refs['personform'].resetFields()
                })
            },
            // 商机跟进附件回调
            uploadchange(file){
                console.log(file);
                this.followForm.file = file.raw
            },
            // 商机跟进确定按钮
            followUpData(){
                this.followLoading = true
                var formData =new FormData()
                formData.append('busStatus',this.followForm.busStatus)
                formData.append('currentFollowTime',this.followForm.currentFollowTime)
                formData.append('nextFollowTime',this.followForm.nextFollowTime)
                formData.append('remark',this.followForm.remark)
                formData.append('busId',this.followForm.busId)
                formData.append('file',this.followForm.file)
                fetchOmsbusinessfollow(formData).then(res => {
                    if(res.data.code === 0){
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                    }else{
                        this.$message({
                            message: '提交失败',
                            type: 'warning'
                        });
                    }
                    this.followLoading = false
                    this.followForm.file = ''
                    this.followVisible = false
                    this.$refs['followform'].resetFields()
                })
            },
            // 授权按钮
            handerAuthorization(){
                if(this.tableselect.length === 1){
                    this.dialogVisible=true
                }else{
                    this.$message({type:'warning',message:'请选择一条数据'});
                }
            },
            // 确认并授权
            addAuthorization(){
                this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                })
                console.log(this.dataList);
                let obj = {
                    "busId": this.tableselect[0].id,
                    "custId": this.tableselect[0].custId,
                    "data": [],
                }
                this.dataList.map( e => {
                    obj.data.push({"proId": e.data.id,"startTime": e.timeDate[0],"endTime": e.timeDate[1]})
                })
                fetchAuthorization(obj).then(res => {
                    console.log(res);
                    this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                    }).close()
                    this.innerVisible = false
                    this.dialogVisible = false
                })
            },
            // 第一层弹窗表格选择的产品id
            firstSelect(e){
                console.log(e);
                let arr = [];
                let prices = 0;
                e.map( ele => {
                    arr.push({data:ele,timeDate:''})
                    prices += ele.budgetAmount
                })
                this.totalPrices = prices
                this.dataList = arr
                console.log(this.totalPrices);
                console.log(this.dataList);
                this.firstSelectId = e
            },
            // 第二层弹窗表格接口数据
            secondTableChange(e){
                this.secondTableData.push(e)
                console.log(this.secondTableData);
            },
            selectionChange(e){
                console.log(e);
                this.tableselect = e
            },
            handleEdit(row,val){
                if(val === 'omsbusinesstransfer'){
                    if(this.tableselect.length != 1){
                        this.$message({type:'warning',message:'请选择一条数据'});
                        return
                    }
                    this.transferVisible=true
                    this.transferForm.id = this.tableselect[0].id
                    this.transferForm.charge = this.tableselect[0].busChargePerson
                    this.transferForm.busAssistPerson = this.tableselect[0].busAssistPerson
                }else if(val === 'omsbusinessperson'){
                    if(this.tableselect.length != 1){
                        this.$message({type:'warning',message:'请选择一条数据'});
                        return
                    }
                    this.personVisible=true
                    this.personForm.id = this.tableselect[0].id
                    this.personForm.charge = this.tableselect[0].busChargePerson
                }else if(val === 'omsbusinessfollow'){
                    if(this.tableselect.length != 1){
                        this.$message({type:'warning',message:'请选择一条数据'});
                        return
                    }
                    this.followVisible=true
                    this.followForm.busId = this.tableselect[0].id
                }else if(val ==='addbusinessfollow'){
                    this.$router.push({ name: 'omsbusinessAdd'})
                }else if(val === 'read'){
                    this.$router.push({name:'examine',params: {id:row.id}})
                }else if(val === 'edit'){
                   this.$router.push({ name: 'omsbusinessAdd', params: { id: row.id,name:row.custName }})
                }else{
                    this.$router.push({name:'omsbusinessfollow',params: {id:row.id}})
                }
            },
            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除?' , '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                addObj(row).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
<style scoped lang='scss'>
    .tabelUnitBox{
        width: 100%;
        .tabelUnitBox_header{
            padding: 0 30px;
            display: flex;
            justify-content: space-between;
            height: 30px;
            width: 100%;
        }
        .tabelUnitBox_time{
            padding-left: 30px;
        }
    }
    .totalPrices{
        padding: 0 30px;
        width: 100%;
        height: 100px;
        background: rgb(211, 211, 211);
        h1{
            text-align: right;
        }
        h2{
            text-align: right;
        }
    }
</style>